#!/bin/bash
source ~/.zshrc

echo "=== CI触发检查 ==="
echo "PR_IID: ${PR_IID}"
echo "COMMENT_BODY: '${COMMENT_BODY}'"

export PR_ID="$PR_IID"
export private_key="bz5pjNJpN2P95FRMDMy4zvyD"

# 检查1：必须有PR编号
if [ -z "$PR_IID" ]; then
    echo "❌ 错误：无PR编号"
    exit 1
fi

# 检查2：如果是评论触发，必须且只能是"retest"
if [ -n "$COMMENT_BODY" ]; then
    # 去除所有空白字符和换行，转换为小写
    CLEANED_COMMENT=$(echo "$COMMENT_BODY" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
    
    echo "清理后评论: '$CLEANED_COMMENT'"
    
    # 必须且只能是"retest"
    if [ "$CLEANED_COMMENT" != "retest" ]; then
        echo "❌ 拒绝：评论必须是且只能是'retest'"
        echo "当前是: '$COMMENT_BODY'"
        exit 0  # 静默退出
    fi
    
    echo "✅ 允许：纯retest评论"
else
    echo "📝 非评论触发（PR创建/更新）"
fi

echo "🚀 执行PR #${PR_IID}的CI"

cd /Users/bytedance/.jenkins/workspace/KotlinNative-CI

# 安全重置代码
echo "重置分支 ${PR_TARGET_BRANCH}..."
git fetch origin "${PR_TARGET_BRANCH}" || { echo "错误：fetch失败"; exit 1; }
git clean -xdf
git reset --hard "origin/${PR_TARGET_BRANCH}" || { echo "错误：reset失败"; exit 1; }

# 合并MR代码
echo "合并MR ${COMMENT_IID}..."
git fetch origin "+refs/merge-requests/${COMMENT_IID}/head:pr_${COMMENT_IID}" || { echo "错误：fetch MR失败"; exit 1; }
git merge "pr_${COMMENT_IID}" || { echo "错误：merge失败"; exit 1; }


cat > local.properties << 'EOF'
kotlin.build.isObsoleteJdkOverrideEnabled=true
kotlin.native.enabled=true
EOF


python3 /Users/bytedance/.jenkins/workspace/CI-passed.py
exit $?
